<template>
  <div class="tabs">
    <el-tabs
      v-model="activeTab"
      type="card"
      @tab-remove="handleTabRemove"
      @tab-click="handleTabClick"
    >
      <el-tab-pane
        v-for="(item, index) in tabList"
        :closable="!!index"
        :key="item.path"
        :label="item.title"
        :name="item.path"
      >
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { useGlobalStore } from '@/store'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { ref, watchEffect } from 'vue'
import { sessionCache } from '@/utils/cache'
import { TAB_LIST } from '@/global/constant'

const router = useRouter()
const route = useRoute()
const globalStore = useGlobalStore()
const { tabList } = storeToRefs(globalStore)

// 监听当前活跃选项卡
const activeTab = ref(route.path)
watchEffect(() => {
  activeTab.value = route.path
})

// 点击选项卡
const handleTabClick = (item) => {
  const path = item.props.name
  // 如果处在选项卡的路由页面了直接返回，没必要再跳一次
  if (path === route.path) return
  router.push(path)
}

// 关闭选项卡
const handleTabRemove = (path: string) => {
  // 1.删除当前选项卡
  const currentIndex = tabList.value.findIndex((item) => item.path === path)
  tabList.value.splice(currentIndex, 1)
  // 2.切换到上一个选项卡
  activeTab.value = tabList.value[currentIndex - 1].path
  // 3.切换到上一个的路由
  router.push(activeTab.value)
  // 4.更新数据
  sessionCache.setCache(TAB_LIST, tabList.value)
}
</script>

<style scoped lang="less">
.tabs {
  width: 90%;
}

.el-tabs {
  --el-tabs-header-height: 34px;
  background-color: #ffffff;
  width: 100%;

  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__content) {
    //overflow: visible;
    display: none;
  }
}
</style>
